package com.azzaou.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.azzaou.dao.IUserDao;
import com.azzaou.model.User;

/**
 * [Description UserDao]
 */
public class UserDao
    extends HibernateDaoSupport implements IUserDao, Serializable
{
  /**
   * Logger for this class
   */
  private static final Logger LOGGER = Logger
      .getLogger(UserDao.class);

  /**
	 * serialVersionUID
	 */
  private static final long serialVersionUID = -5635388779350954722L;

  
  @Override
  public void saveOrUpdate(User User)
  {
    LOGGER.debug("Save Or Update");
    getHibernateTemplate().saveOrUpdate(User);
  }

  
  @Override
  public List<User> getAllUsers()
  {
    Query query = getSession().createQuery("FROM User ");
    List<User> users = query.list() ;
    
    return users;
  }
  
  @Override
  public void deleteUsers(List<Long> listId)
  {
    LOGGER.debug("Delete users");
    String requete = "DELETE FROM User AS um  WHERE um.id IN (:listId) ";
    
    Query query = getSession().createQuery(requete);
    query.setParameterList("listId", listId);
    query.executeUpdate();
  }

  
  @Override
  public Map<Integer, List<User>> getListUsers(int startRecord,int maxPerPage)
  {
    LOGGER.debug("Find User");
    Map<Integer, List<User>> usersMap = new HashMap<Integer, List<User>>();
    String requete = " FROM User ";

    Query qCount = getSession()
        .createQuery(
            " SELECT count(*) FROM User ");
    

    Query query = getSession().createQuery(requete);

    query.setFirstResult(startRecord);
    query.setMaxResults(maxPerPage);
    
    List<User> users = query.list();
    int count = ((Long)qCount.uniqueResult()).intValue();
    usersMap.put(count, users);
    return usersMap;
  }

  
  @Override
  public boolean isUserExist(String login)
  {
    boolean exist = false;
    Query query = getSession()
        .createQuery(
            "FROM User AS u WHERE u.login =:login");
    
    query.setParameter("login", login);
    
    if(query.list().size()>0)
    {
      exist = true;
    }
    return exist;
  }


  @Override
  public List<User> getUserByCreteria(User user) {
	  List<User> userList = new ArrayList<User>();
	  
	  StringBuffer requete = new StringBuffer("FROM User WHERE 1=1 ");

	  if (user != null) {
			if (!StringUtils.isBlank(user.getNom())) {
				requete.append(" AND nom =:nom ");
			}
			if (!StringUtils.isBlank(user.getPrenom())) {
				requete.append(" AND prenom =:prenom ");
			}
			if (!StringUtils.isBlank(user.getStatut())) {
				requete.append(" AND statut =:statut ");
			}
	  }
	  Query query = getSession().createQuery(requete.toString());
	  
	  if (user != null) {
			if (!StringUtils.isBlank(user.getNom())) {
				query.setString("nom", user.getNom());
			}
			if (!StringUtils.isBlank(user.getPrenom())) {
				query.setString("prenom", user.getPrenom());
			}
			if (!StringUtils.isBlank(user.getStatut())) {
				query.setString("statut", user.getStatut());
			}
	  }
	  userList = query.list();
	  return userList;
  }


  @Override
  public User login(String login, String password) {

	   LOGGER.debug("Find Users");
	    User user = null;
	    Query query = getSession().createQuery(
	        "FROM User AS u WHERE u.login= :login AND u.password= :password ");
	    query.setString("login", login);
	    query.setString("password", password);
	    user = (User)query.uniqueResult();

	    return user;
  }


  @Override
  public void delete(User user) {
	  getHibernateTemplate().delete(user);
  }
  
}
